import { edit_info } from '@/services/login';
import { filedlist } from '@/services/platformuser';
import area from '@/utils/area';
import {
  PageContainer,
  ProForm,
  ProFormDatePicker,
  ProFormGroup,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Cascader, Divider, Form, message, Modal, Spin, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';
import AliyunOSSUpload from '../AliyunOSSUpload';

interface Iprops {
  setuserinfo: (show: boolean) => void;
  userinfo: boolean;
  // actionRef: React.MutableRefObject<ActionType | undefined>;
}
const PersonalData = (props: Iprops) => {
  const { setuserinfo, userinfo } = props;
  const formRef = useRef<ProFormInstance>();
  const [form] = Form.useForm();
  // 存储头像
  const [imageUrl, setImageUrl] = useState<any>(undefined);
  // 表单禁用启用
  const [isEdit, setIsEdit] = useState(true);
  // 存储表单数据
  const [formData, setFormData] = useState<any>(undefined);
  const { initialState } = useModel('@@initialState');
  console.log('个人信息', initialState);

  // 获取初始个人资料信息
  useEffect(() => {
    setFormData(initialState?.currentUser);
    setImageUrl(initialState?.currentUser?.head_img);
  }, []);

  // 点击保存按钮
  const handleSave = () => {
    formRef.current?.validateFields().then(async (values) => {
      setFormData(values);
      // 转换生日日期格式
      var d = new Date(values.birth);
      var datetime =
        d.getFullYear() +
        '-' +
        (d.getMonth() + 1) +
        '-' +
        d.getDate() +
        ' ' +
        d.getHours() +
        ':' +
        d.getMinutes() +
        ':' +
        d.getSeconds();

      // 修改个人资料
      let request_body = {
        username: values.username,
        sex: values.sex,
        birth: datetime,
        phone: values.phone,
        marital_status: values.marital_name != undefined ? values.marital_name : 0,
        nation_type: values.nation_type != undefined ? values.nation_type : 0,
        education: values.education != undefined ? values.education : 0,
        province_id: values.area ? values.area[0] : '',
        city_id: values.area ? values.area[1] : '',
        area_id: values.area ? values.area[2] : '',
        address: values.address ? values.address : '',
        head_img: imageUrl,
      };
      console.log('request', request_body);
      // return;

      let res: any = await edit_info(request_body);
      if (res.msg == 'ok') {
        message.success('资料编辑成功！');
        setIsEdit(true);
        setuserinfo(false);
        setTimeout(() => {
          location.reload();
        }, 500);
      } else {
        message.error(res.msg);
      }
    });
  };
  // 点击返回按钮
  const onClickBack = () => {
    // onReset();
    form.setFieldsValue({
      username: initialState?.currentUser?.username,
      sex: initialState?.currentUser?.sex,
      birth: initialState?.currentUser?.birth,
      phone: initialState?.currentUser?.phone,
      marital_name: initialState?.currentUser?.marital_status,
      nation_type: initialState?.currentUser?.nation_type,
      education: initialState?.currentUser?.education,
      address: initialState?.currentUser?.address,
      area: initialState?.currentUser?.province_id
        ? [
            initialState?.currentUser?.province_id,
            initialState?.currentUser?.city_id,
            initialState?.currentUser?.area_id,
          ]
        : null,
    });
    setImageUrl(initialState?.currentUser?.head_img);
    setIsEdit(true);
  };
  // 获取职称列表 获取婚姻状况列表 获取学历列表 获取民族列表
  const get_system_field = async (key: any) => {
    let request_body = {
      type: key,
    };
    let params: any = await filedlist(request_body);
    let res: any = [];
    params.data.map((item: any) => {
      let temp: any = {};
      temp['label'] = item.value;
      temp['value'] = item.key;
      res.push(temp);
    });
    return res;
  };
  // // 重置表单
  // const onReset = () => {
  //   setFormData(initialState?.currentUser);
  //   //头像
  //   setImageUrl(initialState?.currentUser?.head_img);
  // };
  // 直播封面的删除
  const del = () => {
    setImageUrl('');
  };
  return (
    <Modal
      title=""
      centered
      open={userinfo}
      onCancel={() => setuserinfo(false)}
      width={1200}
      destroyOnClose={true}
      footer={null}
      maskClosable={false}
    >
      <PageContainer
        title="个人资料"
        breadcrumb={false}
        header={{
          extra: [
            isEdit ? (
              initialState?.currentUser?.is_master == 1 ? (
                <Tooltip title="管理员禁止编辑个人信息">
                  <Button key="edit" style={{ padding: '0 18px' }} type="primary" disabled>
                    编辑
                  </Button>
                </Tooltip>
              ) : (
                <Button
                  key="edit"
                  style={{ padding: '0 18px' }}
                  type="primary"
                  onClick={() => setIsEdit(false)}
                >
                  编辑
                </Button>
              )
            ) : (
              <div key="box">
                <Button
                  key="save"
                  style={{ padding: '0 18px', marginRight: '20px' }}
                  type="primary"
                  onClick={() => handleSave()}
                >
                  保存
                </Button>
                <Button key="back" style={{ padding: '0 18px' }} onClick={onClickBack}>
                  返回
                </Button>
              </div>
            ),
          ],
        }}
      >
        <Divider />
        <div style={{ width: '1200px', margin: 'auto' }}>
          {formData === undefined ? (
            <div
              style={{
                margin: '20px 0',
                marginBottom: '20px',
                padding: '30px 50px',
                textAlign: 'center',
              }}
            >
              <Spin size="large" />
            </div>
          ) : (
            <ProForm
              formRef={formRef}
              form={form}
              submitter={{
                // 配置按钮的属性
                resetButtonProps: {
                  style: {
                    // 隐藏重置按钮
                    display: 'none',
                  },
                },
                submitButtonProps: {
                  style: {
                    // 隐藏提交按钮
                    display: 'none',
                  },
                },
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <div style={{ width: '70%', flex: '5' }}>
                  <ProFormGroup style={{ marginBottom: '50px' }}>
                    <ProFormText
                      width={280}
                      name="username"
                      label="姓名"
                      disabled={isEdit}
                      placeholder="请输入姓名"
                      rules={[
                        {
                          required: true,
                          message: '请输入姓名',
                          validateTrigger: 'onBlur',
                        },
                      ]}
                      initialValue={formData.username}
                    />
                    <ProFormSelect
                      width={320}
                      name="sex"
                      label="性别"
                      disabled={isEdit}
                      request={async () => [
                        { label: '未知', value: 0 },
                        { label: '男', value: 1 },
                        { label: '女', value: 2 },
                      ]}
                      placeholder="请选择性别"
                      rules={[
                        {
                          required: true,
                          message: '请选择性别',
                        },
                      ]}
                      initialValue={formData.sex}
                    />

                    <ProFormDatePicker
                      width={280}
                      disabled={isEdit}
                      name="birth"
                      label="出生日期"
                      rules={[
                        {
                          required: true,
                          message: '请选择出生日期',
                        },
                      ]}
                      initialValue={formData.birth}
                    />
                  </ProFormGroup>
                  <ProFormGroup style={{ marginBottom: '50px' }}>
                    <ProFormText
                      width={280}
                      name="phone"
                      label="手机号"
                      disabled={isEdit}
                      placeholder="请输入手机号"
                      rules={[
                        {
                          required: true,
                          message: '请输入手机号',
                          validateTrigger: 'onBlur',
                        },
                        {
                          pattern: /^1\d{10}$/,
                          message: '请输入正确的手机号',
                        },
                      ]}
                      initialValue={formData.phone}
                    />
                    <ProFormSelect
                      width={320}
                      name="marital_name"
                      disabled={isEdit}
                      label="婚姻状况"
                      request={async () => get_system_field('marital_status')}
                      placeholder="请选择婚姻状况"
                      initialValue={formData.marital_status}
                    />
                    <ProFormSelect
                      name="nation_type"
                      width={280}
                      disabled={isEdit}
                      label="民族"
                      request={async () => get_system_field('nation_type')}
                      placeholder="请选择民族"
                      initialValue={formData.nation_type}
                    />
                  </ProFormGroup>
                  <ProFormGroup>
                    <ProFormSelect
                      width={280}
                      name="education"
                      disabled={isEdit}
                      label="学历"
                      request={async () => get_system_field('education')}
                      placeholder="请选择学历"
                      initialValue={formData.education}
                    />
                    <Form.Item
                      name="area"
                      label="地址"
                      initialValue={
                        formData.province_id
                          ? [formData.province_id, formData.city_id, formData.area_id]
                          : ''
                      }
                    >
                      <Cascader
                        style={{ width: '320px' }}
                        options={area}
                        disabled={isEdit}
                        // onChange={area_onChange}
                        fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                      />
                    </Form.Item>
                    <ProFormText
                      width={280}
                      name="address"
                      disabled={isEdit}
                      label="详细地址"
                      placeholder="请输入详细地址"
                      initialValue={formData.address}
                    />
                  </ProFormGroup>
                </div>
                <div style={{ width: '30%', flex: '1' }}>
                  <ProForm.Item name="head_img" label="头像">
                    <div>
                      <AliyunOSSUpload
                        status={isEdit}
                        imageUrl={imageUrl}
                        setImageUrl={setImageUrl}
                      ></AliyunOSSUpload>
                    </div>
                    <Button
                      style={{ marginLeft: '20px', marginTop: '20px' }}
                      onClick={del}
                      disabled={isEdit}
                    >
                      删除
                    </Button>
                  </ProForm.Item>
                </div>
              </div>
            </ProForm>
          )}
        </div>
      </PageContainer>
    </Modal>
  );
};
export default PersonalData;
